
#include "stdafx.h"
#include "TimeConvert.h"


static const __int64 SECS_BETWEEN_EPOCHS = 11644473600;
static const __int64 SECS_TO_100NS = 10000000; /* 10^7 */


time_t FileTimeToUnixTime(FILETIME FileTime, long* pNsec)
{
	__int64 UnixTime;
	/* get the full win32 value, in 100ns */
	UnixTime = ((__int64)FileTime.dwHighDateTime << 32) + FileTime.dwLowDateTime;
	/* convert to the Unix epoch */
	UnixTime = UnixTime - (SECS_BETWEEN_EPOCHS * SECS_TO_100NS);
	if (pNsec)
	{
		/* get the number of 100ns, convert to ns */
		*pNsec = (UnixTime % SECS_TO_100NS) * 100;
	}
	UnixTime /= SECS_TO_100NS; /* now convert to seconds */
	if ((time_t)UnixTime != UnixTime)
	{
		AfxMessageBox("Resulting value is too big for a time_t valuen");
	}

	return (time_t)UnixTime;
}

void UnixTimeToFileTime(time_t t, FILETIME* pft)
{
	// Note that LONGLONG is a 64-bit value
	LONGLONG ll = Int32x32To64(t, SECS_TO_100NS) + SECS_BETWEEN_EPOCHS;
	pft->dwLowDateTime = (DWORD)ll;
	pft->dwHighDateTime = ll >> 32;
}
